import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
matplotlib.use('TkAgg')

sns.set(style="whitegrid")

class ParkingDemandSupplyModel:
    def __init__(self, population_data, total_population):
        self.population_data = population_data
        self.total_population = total_population

    def calculate_demand(self):
        self.population_data['Demand'] = self.population_data['d'] * 100

    def calculate_supply(self, parking_spaces):
        self.population_data['Supply'] = parking_spaces

    def adjust_license_price(self, base_price, alpha):
        self.population_data['License Price'] = base_price * (1 + alpha * (self.population_data['Demand'] / self.population_data['Supply'] - 1))

    def calculate_population_ratio(self):
        self.population_data['Population Ratio'] = self.population_data['Population Census 2020-11-01'] / self.total_population


file_path = 'population_of_Beijing.xlsx'
df = pd.read_excel(file_path, engine='openpyxl')

# 设置字体为黑体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

total_population = df['Population Census 2020-11-01'].sum()

model = ParkingDemandSupplyModel(df, total_population)

model.calculate_demand()

parking_spaces = df['number']
model.calculate_supply(parking_spaces)

base_price = 100
alpha = 0.01
model.adjust_license_price(base_price, alpha)

model.calculate_population_ratio()

print(model.population_data[['Native', 'Population Ratio', 'Demand', 'Supply', 'License Price']])

output_file_path = 'population_ratio_results1.xlsx'
model.population_data.to_excel(output_file_path, index=False, engine='openpyxl')

# 生成图表并显示
plt.figure(figsize=(14, 8))

# 子图1：展示各区域人口比例
plt.subplot(1, 2, 1)
sns.barplot(x='Native', y='Population Ratio', data=model.population_data)
plt.title('Population Ratio by District')
plt.xticks(rotation=90)
plt.xlabel('Districts')
plt.ylabel('Population Ratio')

# 子图2：展示需求与许可价格关系
plt.subplot(1, 2, 2)
sns.scatterplot(x='Demand', y='License Price', hue='Native', data=model.population_data, s=100, edgecolor=None)
plt.title('License Price vs Demand')
plt.xlabel('Demand (Number of People)')
plt.ylabel('License Price (Yuan)')

# 调整布局
plt.tight_layout()

# 直接显示图形
plt.show()
